<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login-form"
          label-width="auto"
          :model="form"
          :rules="rules"
          ref="loginFormRef"
        >
          <h1>Hello</h1>
          <h2>硅谷甄选管理系统</h2>
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              size="default"
              class="login-btn"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="index">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import useUserStore from '@/store/modules/user.ts'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time.ts'
const userStore = useUserStore()
//获取路由器
let $router = useRouter()

let route = useRoute()
//控制加载效果
const loading = ref(false)
const form = reactive({
  username: 'admin',
  password: '123456',
})
//获取el-form组件
let loginFormRef = ref()
//提交
/*const submit = async (form: FormInstance | undefined) => {
  console.log('form =>', form)
  if(!form) return
  await form.validate((valid,fields)=>{
    console.log('valid =>',valid)
    console.log('fields =>',fields)
    if(!valid) return
    console.log('提交成功')
  })
}*/
//登录
const login = async () => {
  console.log('loginFormRef====>', loginFormRef)
  //保证表单项验证通过
  console.log('loginFormRef.value ====>', loginFormRef.value)
  await loginFormRef.value.validate()
  //开始加载
  loading.value = true

  console.log('res=>')
  //调用登录接口
  //登录失败后提示错误信息
  try {
    await userStore.login(form)
    //登录成功，跳转首页
    //判断登录的时候是否有query参数
    if (route.query.redirect) {
      $router.push(route.query.redirect as string)
    } else {
      $router.push('/home')
    }
    //
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: 'hi，' + getTime() + '好!',
    })
    //加载效果消失
    loading.value = false
  } catch (err) {
    //加载效果消失
    loading.value = false
    console.log('err=>', err)
    ElNotification({
      type: 'error',
      message: (err as Error).message,
    })
  }
}
const validateUsername = (_rule: any, value: string, callback: any) => {
  //role:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length < 5) {
    callback(new Error('用户名不能小于5位'))
  } else {
    callback()
  }
}
const validatePwd = (_rule: any, value: string, callback: any) => {
  if (value.length < 6) {
    callback(new Error('密码不能小于6位'))
  } else {
    callback()
  }
}
const rules = {
  username: [
    //规则对象属性:
    //required,代表这个字段务必要校验的
    //min:文本长度至少多少位
    //max:文本长度最多多少位
    //message:错误的提示信息
    //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
    // {required: true, message: '用户名不能为空', trigger: 'blur'},
    { min: 5, max: 8, message: '用户名长度需在5-8位', trigger: 'change' },
    //自定义校验规则
    { validator: validateUsername, trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    // {min: 6, max: 8, message: '密码长度需在6-8位', trigger: 'change'},
    { validator: validatePwd, trigger: 'change' },
  ],
}
</script>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;
  .login-form {
    position: relative;
    top: 40vh;
    width: 80%;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;
    h1 {
      color: white;
      font-size: 30px;
    }
    h2 {
      color: white;
      font-size: 20px;
      margin: 20px 0;
    }
    .login-btn {
      width: 100%;
    }
  }
}
:deep(.el-form-item__label) {
  color: black;
}
</style>
